package com.dynabook.ems.model.listener;

import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.exception.ExcelDataConvertException;
import cn.idev.excel.read.listener.ReadListener;
import com.dynabook.ems.model.entity.EmsCategory;
import com.dynabook.ems.service.EmsCategoryService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class EmsCategoryListener implements ReadListener<EmsCategory> {

    private final EmsCategoryService emsCategoryService;
    
    // 统计成功和失败的记录数
    private int successCount = 0;
    private int failCount = 0;
    
    public EmsCategoryListener(EmsCategoryService emsCategoryService) {
        this.emsCategoryService = emsCategoryService;
    }
    
    @Override
    public void invoke(EmsCategory emsCategory, AnalysisContext analysisContext) {
        try {
            log.info("解析到一条分类数据:{}", emsCategory.toString());
            
            // 直接尝试插入单条数据，不处理错误
            try {
                // 使用save方法插入单条数据
                boolean success = emsCategoryService.save(emsCategory);
                if (success) {
                    successCount++;
                } else {
                    failCount++;
                    log.warn("插入分类数据失败，可能是重复数据: {}", emsCategory.getItemCode());
                }
            } catch (Exception e) {
                // 捕获异常但不处理，只记录日志
                failCount++;
                log.warn("插入分类数据异常，可能是唯一索引冲突: {}, 错误: {}", emsCategory.getItemCode(), e.getMessage());
            }
            
        } catch (Exception e) {
            log.error("解析单条分类数据失败，数据内容: {}，异常信息: {}", emsCategory, e.getMessage());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 所有数据解析完成后，输出统计信息
        log.info("所有分类数据解析完成，成功插入: {}条，失败: {}条", successCount, failCount);
    }
    
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        }
        // 不抛出异常，继续处理下一行
        // throw exception;
    }
}
